package de.lindenvalley.sevmob.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpConnect implements ConnectInterface {

	private DefaultHttpClient httpClient;
	private StringBuilder sb = new StringBuilder();

	@Override
	public boolean connect(String host) {
		httpClient = new DefaultHttpClient();
		return true;
	}

	@Override
	public void disconnect() {
		// TODO Auto-generated method stub

	}

	@Override
	public String post(String serverUrl, List<NameValuePair> data) {
		if (httpClient == null){
			connect(null);
		}
		String responseString = null;
		HttpPost requestPost = new HttpPost(serverUrl);
		try {
			requestPost.setEntity(new UrlEncodedFormEntity(data));
			HttpResponse response = httpClient.execute(requestPost);
			if (response.getEntity() != null){
				sb.setLength(0);
				sb.trimToSize();
				BufferedReader in = new BufferedReader
			            (new InputStreamReader(response.getEntity().getContent()));
				String line;
				while ((line = in.readLine()) != null) {
//	                sb.append(line + NL);
	            	sb.append(line);
	            }
				responseString = sb.toString();
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return responseString;
	}

}
